package pres.moling.common.tool;



import pres.moling.common.tool.reflect.ReflectUtil;

import java.io.File;
import java.util.*;

/**
 * map 工具类
 *
 * @author moling
 */
public interface MapHelper {

    static <K, V> HashMap<K, V> newHashMap() {return new HashMap<>();}

    static <K, V> HashMap<K, V> newHashMap(int size) {return new HashMap<>(size);}

    static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {return new LinkedHashMap<>();}

    static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int size) {return new LinkedHashMap<>(size);}


    static <K, V> TreeMap<K, V> newTreeMap() {return new TreeMap<>();}


    static <k, v> boolean isEmpty(Map<k, v> map) {
        return map == null || map.isEmpty();
    }

    static <k, v> boolean isNotEmpty(Map<k, v> map) {
        return !isEmpty(map);
    }


    static Map<String, Object> readJSON(File file) {
        return null;
    }

    static String getStr(Map<String, Object> map, String key) {
        return ConvertHelper.castToStr(map.get(key));
    }

    static Boolean getBoolean(Map<String, Object> map, String key) {
        return ConvertHelper.castToBoolean(map.get(key));
    }

    static Date getDate(Map<String, Object> map, String key) {
        return ConvertHelper.castToDate(map.get(key));
    }


    /**
     * map对象转实体类
     *
     * @param map         要转换的map
     * @param clazz       要转换的类对象
     * @param isCamelCase 是否下换线转驼峰
     * @return 转换后的类对象
     */
    static <T> T mapToBean(Map<String, Object> map, Class<T> clazz, boolean isCamelCase) {
        T entity = ReflectUtil.newInstance(clazz);
        map.forEach((k, v) -> ReflectUtil.setField(entity, isCamelCase ? StrHelper.lineToHump(k) : k, v));
        return entity;
    }

    static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        return mapToBean(map, clazz, false);
    }

    /**
     * 将map对象的属性值赋给对象
     *
     * @param map         要赋值的map
     * @param entity      要赋值的对象
     * @param isOverWrite 是否覆写
     * @param <T>         泛型
     */
    private static <T> void fillBean(Map<String, Object> map, T entity, boolean isOverWrite) {
        map.forEach((k, v) -> {
            if (isOverWrite || Objects.isNull(ReflectUtil.getFieldValue(entity, k))) {
                ReflectUtil.setField(entity, k, v);
            }
        });
    }
}
